import { get, add } from "../../utils/db";
import {  multiUpload } from "../../utils/upload";
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: "",  //名称
    typeList: [],    //分类列表
    typeid: '',
    info: "",
    files: [],     //图片临时地址
    error: "",     //错误信息

  },
  async onLoad() {
   
    //读取菜谱分类
    let result = await get({ collection: "type" }).catch(err => {
      console.log(err)
    })
    //获取默认的分类id

    this.data.typeid=result.data[0]._id;
    // console.log(result)
    this.setData({
      typeList: result.data
    })

  },
  //选择菜谱分类
  typeChange(e) {
    // console.log(e)
    this.data.typeid = e.detail.value;
  },
  //选择图片
  imgSelect(e) {
    // console.log(e)
    let files = e.detail.tempFilePaths;//图片临时地址
    let result = files.map(item => {
      return { url: item }
    })
    // console.log(result)
    this.setData({
      files: result
    })
  },
  //提交表单
  async mySubmit() {

    //验证表单
    if (this.data.name == "") {
      this.setData({
        error: "请填写菜单名称"
      })
      return;
    }
    if (this.data.typeid == "") {
      this.setData({
        error: "请选择分类"
      })
      return;
    }
    if (this.data.files.length == 0) {
      this.setData({
        error: "请选择图片"
      })
      return;
    }
    if (this.data.info == "") {
      this.setData({
        error: "请填写菜品做法"
      })
      return;
    }

    //显示loading样式
    wx.showLoading({
      title: '正在提交',
      mask: true
    })

    //files 对象数组  [{url:"**.png"},{url:"***.png"}]
    let image = await multiUpload(this.data.files).catch(err => {
      console.error(err)
    })


    //2.保存数据库
    let formData = {
      image: image,
      name: this.data.name,
      typeid: this.data.typeid,
      nickName: app.globalData.userInfo.nickName,
      avatarUrl: app.globalData.userInfo.avatarUrl,
      likes: 0,
      views: 0,
      info: this.data.info,
      addtime: new Date().getTime()
    }
    //把表单内容添加到数据库
    let res = await add({ collection: "menu", data: formData }).catch(err => {
      console.error(err)
    })
    console.log(res)

    //隐藏loading框
    wx.hideLoading()
    wx.showToast({
      title: '添加成功'
    })


    setTimeout(() => {
      //跳转到my页面
      wx.reLaunch({
        url: '/pages/my/my',
      })
    }, 1500)
  }


})